const db = require('../models');

const SudokuPuzzle = db.SudokuPuzzle;
const SudokuAnswer = db.SudokuAnswer;
const SudokuAction = db.SudokuAction;
const User = db.User;

/**
 * 数独游戏控制器
 */
const gameController = {
  /**
   * 记录用户操作
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   * @param {Function} next 下一个中间件
   */
  async recordAction(req, res, next) {
    try {
      const { userId, puzzleId, actionType, cellIndex, value } = req.body;
      
      if (!userId || !puzzleId || !actionType || cellIndex === undefined) {
        return res.status(400).json({
          code: 400,
          message: '用户ID、题目ID、操作类型和格子索引不能为空'
        });
      }
      
      // 验证操作类型
      const validActionTypes = ['fill', 'erase', 'hint', 'undo'];
      if (!validActionTypes.includes(actionType)) {
        return res.status(400).json({
          code: 400,
          message: '无效的操作类型'
        });
      }
      
      // 验证格子索引
      if (cellIndex < 0 || cellIndex > 80) {
        return res.status(400).json({
          code: 400,
          message: '格子索引必须在0-80之间'
        });
      }
      
      // 创建操作记录
      const action = await SudokuAction.create({
        userId,
        puzzleId,
        actionType,
        cellIndex,
        value: value || null,
        creator: `user_${userId}`
      });
      
      res.json({
        code: 0,
        message: '记录操作成功',
        data: {
          actionId: action.id,
          actionTime: action.actionTime
        }
      });
    } catch (error) {
      next(error);
    }
  },

  /**
   * 获取新游戏题目
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象  
   * @param {Function} next 下一个中间件
   */
  async createNewPuzzle(req, res, next) {
    try {
      const { userId, level = 'easy' } = req.body;
      
      console.log(`[DEBUG] 获取游戏题目 - 用户ID: ${userId}, 难度: ${level}`);
      
      if (!userId) {
        return res.status(400).json({
          code: 400,
          message: '用户ID不能为空'
        });
      }
      
      let nextPuzzle;
      let lastCompletedId = 0; // 默认从0开始，表示从第一题开始
      
      // 首先检查题库中是否有该难度的题目
      const totalPuzzles = await SudokuPuzzle.count({
        where: {
          level,
          isDeleted: '0'
        }
      });
      
      console.log(`[DEBUG] 题库中${level}难度题目总数: ${totalPuzzles}`);
      
      if (totalPuzzles === 0) {
        console.log(`[ERROR] 题库中没有${level}难度的题目`);
        
        // 检查数据库连接
        try {
          await db.sequelize.authenticate();
          console.log('[DEBUG] 数据库连接正常');
          
          // 检查表是否存在
          const tableExists = await db.sequelize.getQueryInterface().showAllTables();
          console.log('[DEBUG] 数据库中的表:', tableExists);
          
        } catch (dbError) {
          console.log('[ERROR] 数据库连接失败:', dbError.message);
        }
        
        return res.status(404).json({
          code: 404,
          message: `题库中暂无${level}难度的题目，请检查数据库或联系管理员`
        });
      }
      
      // 查找用户最后完成的题目
      const lastAnswer = await SudokuAnswer.findOne({
        where: {
          userId,
          isDeleted: '0',
          isCorrect: true // 只考虑正确完成的题目
        },
        include: [{
          model: SudokuPuzzle,
          as: 'puzzle',
          where: { level }
        }],
        order: [['finishedAt', 'DESC']]
      });
      
      if (lastAnswer) {
        lastCompletedId = lastAnswer.puzzleId;
        console.log(`[DEBUG] 用户${userId}最后完成的题目ID: ${lastCompletedId}`);
      } else {
        console.log(`[DEBUG] 用户${userId}是新用户，从第一题开始`);
      }
      
      // 根据上次完成的题目ID，获取下一个题目（利用ID自增特性）
      nextPuzzle = await SudokuPuzzle.findOne({
        where: {
          level,
          isDeleted: '0',
          id: {
            [db.Sequelize.Op.gt]: lastCompletedId // 大于上次完成的题目ID（新用户为0）
          }
        },
        order: [['id', 'ASC']] // 按ID升序，获取最小的下一个ID
      });
      
      // 如果没有找到下一个题目，说明已经完成了所有题目，重新开始
      if (!nextPuzzle) {
        console.log(`[DEBUG] 没有找到下一题，从第一题重新开始`);
        nextPuzzle = await SudokuPuzzle.findOne({
          where: {
            level,
            isDeleted: '0'
          },
          order: [['id', 'ASC']]
        });
      }
      
      if (!nextPuzzle) {
        console.log(`[ERROR] 查询失败，无法获取任何题目`);
        return res.status(500).json({
          code: 500,
          message: `获取题目失败，请重试或联系管理员`
        });
      }
      
      console.log(`[DEBUG] 成功获取题目ID: ${nextPuzzle.id}`);
      
      res.json({
        code: 0,
        message: '获取题目成功',
        data: {
          id: nextPuzzle.id,
          level: nextPuzzle.level,
          puzzle: nextPuzzle.puzzle,
          solution: nextPuzzle.solution,
          clues: nextPuzzle.clues
        }
      });
    } catch (error) {
      next(error);
    }
  },

  /**
   * 提交游戏答案
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   * @param {Function} next 下一个中间件
   */
  async submitAnswer(req, res, next) {
    try {
      const { userId, puzzleId, answer, timeUsed } = req.body;
      
      if (!userId || !puzzleId || !answer) {
        return res.status(400).json({
          code: 400,
          message: '用户ID、题目ID和答案不能为空'
        });
      }
      
      // 查找题目
      const puzzle = await SudokuPuzzle.findByPk(puzzleId);
      
      if (!puzzle) {
        return res.status(404).json({
          code: 404,
          message: '题目不存在'
        });
      }
      
      // 检查用户是否已经解答过此题
      let existingAnswer = await SudokuAnswer.findOne({
        where: {
          userId,
          puzzleId: puzzleId,
          isDeleted: '0'
        }
      });
      
      // 验证答案是否正确
      const answerStr = Array.isArray(answer) 
        ? answer.flat().join('') 
        : answer.toString();
      
      const isCorrect = answerStr === puzzle.solution;
      
      let sudokuAnswer;
      
      if (existingAnswer) {
        // 如果已经完成过，不允许再次提交
        if (existingAnswer.finishedAt) {
          return res.status(400).json({
            code: 400,
            message: '您已经完成过此题目'
          });
        }
        
        // 更新暂存记录为完成状态
        await existingAnswer.update({
          answer: answerStr,
          isCorrect,
          timeUsed: timeUsed || 0,
          finishedAt: new Date(),
          modifier: `user_${userId}`
        });
        sudokuAnswer = existingAnswer;
      } else {
        // 创建新的解答记录
        sudokuAnswer = await SudokuAnswer.create({
          userId,
          puzzleId: puzzleId,
          answer: answerStr,
          isCorrect,
          timeUsed: timeUsed || 0,
          finishedAt: new Date(),
          creator: `user_${userId}`
        });
      }
      
      res.json({
        code: 0,
        message: '提交答案成功',
        data: {
          isCorrect,
          answerId: sudokuAnswer.id,
          timeUsed: sudokuAnswer.timeUsed,
          correctAnswer: isCorrect ? null : puzzle.solution // 只有答错时才返回正确答案
        }
      });
    } catch (error) {
      next(error);
    }
  },

  /**
   * 获取用户解答历史
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   * @param {Function} next 下一个中间件
   */
  async getUserAnswers(req, res, next) {
    try {
      const { userId } = req.query;
      const { page = 1, limit = 10 } = req.query;
      
      if (!userId) {
        return res.status(400).json({
          code: 400,
          message: '用户ID不能为空'
        });
      }
      
      const offset = (page - 1) * limit;
      
      const answers = await SudokuAnswer.findAndCountAll({
        where: {
          userId,
          isDeleted: '0'
        },
        include: [{
          model: SudokuPuzzle,
          as: 'puzzle',
          attributes: ['level', 'clues']
        }],
        order: [['finishedAt', 'DESC']],
        limit: parseInt(limit),
        offset: offset
      });
      
      res.json({
        code: 0,
        message: '获取解答历史成功',
        data: {
          answers: answers.rows,
          total: answers.count,
          page: parseInt(page),
          limit: parseInt(limit)
        }
      });
    } catch (error) {
      next(error);
    }
  },

  /**
   * 保存游戏进度（暂存）
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   * @param {Function} next 下一个中间件
   */
  async saveProgress(req, res, next) {
    try {
      const { userId, puzzleId, answer, timeUsed, mistakes, hintsUsed } = req.body;
      
      if (!userId || !puzzleId || !answer) {
        return res.status(400).json({
          code: 400,
          message: '用户ID、题目ID和当前进度不能为空'
        });
      }

      // 查找是否已存在该用户的该题目记录
      let progress = await SudokuAnswer.findOne({
        where: {
          userId,
          puzzleId,
          isDeleted: '0'
        }
      });

      const answerStr = Array.isArray(answer) 
        ? answer.flat().join('') 
        : answer.toString();

      if (progress) {
        // 如果已完成，不允许再暂存
        if (progress.finishedAt) {
          return res.status(400).json({
            code: 400,
            message: '该题目已完成，无法暂存'
          });
        }

        // 更新进度
        await progress.update({
          answer: answerStr,
          timeUsed: timeUsed || 0,
          mistakes: mistakes || 0,
          hintsUsed: hintsUsed || 0,
          modifier: `user_${userId}`
        });
      } else {
        // 创建新的进度记录
        progress = await SudokuAnswer.create({
          userId,
          puzzleId,
          answer: answerStr,
          isCorrect: null, // 暂存时为null
          timeUsed: timeUsed || 0,
          mistakes: mistakes || 0,
          hintsUsed: hintsUsed || 0,
          finishedAt: null, // 暂存时为null
          creator: `user_${userId}`
        });
      }

      res.json({
        code: 0,
        message: '保存进度成功',
        data: {
          id: progress.id,
          savedAt: progress.modified_at || progress.startedAt
        }
      });
    } catch (error) {
      next(error);
    }
  },

  /**
   * 获取游戏进度
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   * @param {Function} next 下一个中间件
   */
  async getProgress(req, res, next) {
    try {
      const { userId, puzzleId } = req.query;
      
      if (!userId || !puzzleId) {
        return res.status(400).json({
          code: 400,
          message: '用户ID和题目ID不能为空'
        });
      }

      // 查找进度记录（未完成的）
      const progress = await SudokuAnswer.findOne({
        where: {
          userId,
          puzzleId,
          finishedAt: null, // 只查找未完成的
          isDeleted: '0'
        },
        include: [{
          model: SudokuPuzzle,
          as: 'puzzle',
          attributes: ['id', 'level', 'puzzle', 'solution']
        }]
      });

      if (!progress) {
        return res.json({
          code: 0,
          message: '没有找到进度记录',
          data: null
        });
      }

      res.json({
        code: 0,
        message: '获取进度成功',
        data: {
          id: progress.id,
          userId: progress.userId,
          puzzleId: progress.puzzleId,
          currentBoard: progress.answer,
          timeUsed: progress.timeUsed,
          mistakes: progress.mistakes,
          hintsUsed: progress.hintsUsed,
          startedAt: progress.startedAt,
          puzzle: progress.puzzle
        }
      });
    } catch (error) {
      next(error);
    }
  }
};

module.exports = gameController;